(function() {

	GameFlip = function(rpc) {
		this.rpc = rpc;
		this.is_upside_down = null;
		this.options = {
				frequency : 500
			};
		this.is_background = false;
	};

	GameFlip.prototype = {
		start : function(is_background) {
			this.is_background = is_background;
			this.watchID = navigator.accelerometer.watchAcceleration(
					this.sensor_changed.bind(this), this.on_error.bind(this),
					this.options);
		},

		sensor_changed : function(a) {
			var prev = this.is_upside_down;
			if(Math.abs(a.x) < 3 && Math.abs(a.y) < 3 ) {
				if(a.z > 8) {
					this.is_upside_down = false;
				} else {
					this.is_upside_down = true;
				}
			}
			if(prev !== this.is_upside_down) {
				this.rpc.send_is_upside_down(this.is_upside_down);
			}
			//this.debug(a);
		},
		stop : function() {
			if (this.watch_id) {
				navigator.accelerometer.clearWatch(this.watch_id);
				this.watch_id = null;
			}
		},
		debug : function(a) {
			var element = document.getElementById('debug');
	        element.innerHTML = 'Acceleration X: ' + a.x + '<br />' +
            'Acceleration Y: ' + a.y + '<br />' +
            'Acceleration Z: ' + a.z + '<br />' +
            'Timestamp: '      + a.timestamp + '<br />' +
            'Upside down:'	   + this.is_upside_down;
		},
		on_error: function() {
			alert("game shake - error!");
			this.stop();
			this.start();
			
		}
	};
})();